package com.bawei.module_mine.ui

import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.lib_mvi.base.BaseActivity
import com.bawei.lib_storage.database.HistoryManager
import com.bawei.module_mine.R
import com.bawei.module_mine.adapter.HistoryAdapter
import com.bawei.module_mine.databinding.ActivityHistoryBinding
import com.bawei.module_mine.utils.HistoryRefreshManager
import com.bawei.lib_common.event.HistoryRefreshEvent
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

@Route(path = "/mine/HistoryActivity")
class HistoryActivity : BaseActivity() {
    
    private val binding by lazy {
        ActivityHistoryBinding.inflate(layoutInflater)
    }
    
    private lateinit var historyAdapter: HistoryAdapter
    
    override fun getLayoutRootView(): View {
        return binding.root
    }
    
    override fun initView() {
        super.initView()
        setupViews()
        setupRecyclerView()
        loadHistoryData()
        
        // 注册到刷新管理器
        HistoryRefreshManager.registerHistoryActivity(this)
        
        // 注册EventBus
        EventBus.getDefault().register(this)
    }
    
    private fun setupViews() {
        // 设置返回按钮
        binding.ivCollectBack.setOnClickListener {
            finish()
        }
        
        // 设置标题
//        binding.tvCollectTitle.text = "观看历史"
    }
    
    private fun setupRecyclerView() {
        historyAdapter = HistoryAdapter(
            onItemClick = { historyItem ->
                // 点击历史记录项，可以跳转到视频详情页
                Toast.makeText(this, "播放视频: ${historyItem.title}", Toast.LENGTH_SHORT).show()
            },
            onDeleteClick = { historyItem ->
                // 删除历史记录
                deleteHistoryItem(historyItem)
            }
        )
        
        binding.rvCollectList.apply {
            layoutManager = LinearLayoutManager(this@HistoryActivity)
            adapter = historyAdapter
        }
    }
    
    private fun loadHistoryData() {
        lifecycleScope.launch {
            try {
                // 这里使用默认用户ID，实际应用中应该从用户管理器中获取
                val userId = "default_user"
                val historyList = HistoryManager.getAllHistory(userId)
                
                if (historyList.isEmpty()) {
                    showEmptyState()
                } else {
                    showHistoryList(historyList)
                }
            } catch (e: Exception) {
                e.printStackTrace()
                Toast.makeText(this@HistoryActivity, "加载历史记录失败", Toast.LENGTH_SHORT).show()
                showEmptyState()
            }
        }
    }
    
    private fun showEmptyState() {
        binding.rvCollectList.visibility = View.GONE
        binding.tvCollectEmpty.visibility = View.VISIBLE
        binding.tvCollectEmpty.text = "暂无观看历史"
    }
    
    private fun showHistoryList(historyList: List<com.bawei.lib_storage.database.entity.HistoryVideoEntity>) {
        binding.rvCollectList.visibility = View.VISIBLE
        binding.tvCollectEmpty.visibility = View.GONE
        historyAdapter.submitList(historyList)
    }
    
    private fun deleteHistoryItem(historyItem: com.bawei.lib_storage.database.entity.HistoryVideoEntity) {
        lifecycleScope.launch {
            try {
                val userId = "default_user"
                val success = HistoryManager.removeHistory(historyItem.videoId, userId)
                
                if (success) {
                    Toast.makeText(this@HistoryActivity, "已删除", Toast.LENGTH_SHORT).show()
                    // 重新加载数据
                    loadHistoryData()
                } else {
                    Toast.makeText(this@HistoryActivity, "删除失败", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                e.printStackTrace()
                Toast.makeText(this@HistoryActivity, "删除失败", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    /**
     * 刷新历史记录数据
     * 供外部调用，实现实时刷新
     */
    fun refreshHistoryData() {
        loadHistoryData()
    }
    
    override fun onDestroy() {
        super.onDestroy()
        // 注销刷新管理器
        HistoryRefreshManager.unregisterHistoryActivity()
        
        // 注销EventBus
        EventBus.getDefault().unregister(this)

        HistoryRefreshManager.unregisterHistoryActivity()
        EventBus.getDefault().unregister(this)
    }
    
    /**
     * 接收历史记录刷新事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onHistoryRefreshEvent(event: HistoryRefreshEvent) {
        // 刷新历史记录数据
        loadHistoryData()
    }


}